package Utils.UI;

import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Text;
import org.eclipse.swt.widgets.Widget;

import Utils.Graphics.LoadingWheel;

/**
 * UIUpdater simulates the execution of a "UI thread" on a single display (of
 * the current widget) using the SWT asyncExec method. It consists of basic
 * operations on widgets we will use.
 * 
 * @author micha
 * 
 */

public class UIUpdater {

	public static void setWidgetText(final Widget widget, final String text) {

		widget.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (widget.isDisposed())
					return;

				if (widget instanceof Label) {
					((Label) widget).setText(text);
				}

				else if (widget instanceof Text) {
					((Text) widget).setText(text);
				}
			}
		});
	}

	public static void setWidgetVisibile(final Widget widget,
			final boolean visible) {

		widget.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (widget.isDisposed())
					return;

				if (widget instanceof Label) {
					((Label) widget).setVisible(visible);
				}

				else if (widget instanceof Text) {
					((Text) widget).setVisible(visible);
				}

				else if (widget instanceof Button) {
					((Button) widget).setVisible(visible);
				}

			}
		});
	}

	public static void setWidgetEnable(final Widget widget, final boolean enable) {

		widget.getDisplay().asyncExec(new Runnable() {
			public void run() {
				if (widget.isDisposed())
					return;

				if (widget instanceof Label) {
					((Label) widget).setEnabled(enable);
				}

				else if (widget instanceof Text) {
					((Text) widget).setEnabled(enable);
				}

				else if (widget instanceof Button) {
					((Button) widget).setEnabled(enable);
				}

			}
		});
	}

	public static void setWheel(final Display display,
			final LoadingWheel wheel, final boolean active) {

		Thread t = new Thread() {
			@Override
			public void run() {
				try {
					display.asyncExec(new Runnable() {
						public void run() {
							if (active) {
								wheel.start();
							} else {
								wheel.stop();
							}

						}
					});
				} catch (Exception e) {
				}

			}
		};

		t.start();

	}
}
